import { Application, codo } from "egg";
import WeWorkBaseService from "./WeWorkBaseService";
import { WeWork } from "./type";
import CodoError from "../CodoError";

export default class User extends WeWorkBaseService {
	constructor(
		protected config: codo.WeWork.IWeWorkConfig,
		private accessToken: string,
		protected app: Application
	) {
		super(config, app);
	}

	/**
	 *创建成员用户
	 *
	 * @param {qiwei.IUserCreate} data
	 * @memberof PlatformQiyeWeixinUserService
	 *  - http://developer.work.weixin.qq.com/document/path/90195
	 */
	async create(data: WeWork.IUserCreate) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=${this.accessToken}&debug=1`;
		const res = await this.curl<WeWork.IResponse>(url, {
			method: "POST",
			dataType: "json",
			contentType: "json",
			data,
		});
		if (res.data.errcode === 0) {
			return true;
		}
		this.app.logger.error("[企业微信 创建成员] 错误 %s", res.data.errmsg);
		throw new CodoError(res.data.errmsg);
	}

	/**
	 *删除成员用户
	 *
	 * @param {string} userid
	 * @memberof PlatformQiyeWeixinUserService
	 *  - http://developer.work.weixin.qq.com/document/path/90198
	 */
	async delete(userid: string) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=${this.accessToken}&userid=${userid}`;
		const res = await this.curl<WeWork.IResponse>(url, {
			method: "GET",
			dataType: "json",
		});
		if (res.data.errcode === 0) {
			return true;
		}
		this.app.logger.error("[企业微信 删除成员] 错误 %s", res.data.errmsg);
		throw new CodoError(res.data.errmsg);
	}

	/**
	 *读取一个成员的详细信息
	 *
	 * @param {string} userid 用户成员的userid
	 * @return {*}
	 * @memberof PlatformQiyeWeixinUserService
	 *  -https://developer.work.weixin.qq.com/document/path/90196
	 */
	async getOneUserInfo(userid: string) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=${this.accessToken}&userid=${userid}`;
		type Response = WeWork.IUserInfo & WeWork.IResponse;
		const res = await this.curl<Response>(url, {
			method: "GET",
			dataType: "json",
		});
		if (res.data.errcode === 0) {
			return res.data;
		}
		this.app.logger.error("[企业微信 读取一个成员] 错误 %s", res.data.errmsg);
		throw new CodoError(res.data.errmsg);
	}

	/**
	 * 查询成员详情列表 by 部门id
	 * - 接口已废弃，企微安全机制，无法再查询
	 *
	 * @param {number} partId
	 * @memberof PlatformQiyeWeixinUserService
	 *  - https://developer.work.weixin.qq.com/document/path/90201
	 */
	async getUserInfoListByPart(partId: number) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=${this.accessToken}&department_id=${partId}&fetch_child=1`;
		type Response = { userlist: WeWork.IUserInfo[] } & WeWork.IResponse;
		const res = await this.curl<Response>(url, {
			method: "GET",
			dataType: "json",
		});
		if (res.data.errcode === 0) {
			return res.data.userlist;
		}
		this.app.logger.error("[企业微信 获取部门成员列表] 错误 %s", res.data.errmsg);
		throw new CodoError(res.data.errmsg);
	}

	/**
	 *禁用、解禁成员（使用的修改接口）
	 *
	 * @param {string} userid
	 * @param {1 | 0} isEnable 1启用 0禁用
	 * @memberof PlatformQiyeWeixinUserService
	 *  - https://developer.work.weixin.qq.com/document/path/90197
	 */
	async disabledOneUser(userid: string, isEnable: 1 | 0) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=${this.accessToken}`;
		const data: Partial<WeWork.IUserCreate> = {
			userid,
			enable: isEnable,
		};
		const res = await this.curl<WeWork.IResponse>(url, {
			method: "POST",
			dataType: "json",
			contentType: "json",
			data,
		});
		if (res.data.errcode === 0) {
			return true;
		}
		this.app.logger.error("[企业微信 禁用、解禁成员] 错误 %s", res.data.errmsg);
		throw new CodoError(res.data.errmsg);
	}

	/**
	 *邀请成员使用企业微信，会下发短信或邮件通知
	 *
	 * @param {string[]} useridList
	 * @memberof PlatformQiyeWeixinUserService
	 * - http://developer.work.weixin.qq.com/document/path/90975
	 */
	async inviteUser(useridList: string[]) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/batch/invite?access_token=${this.accessToken}`;
		type Response = { invaliduser: string[] } & WeWork.IResponse;
		const res = await this.curl<Response>(url, {
			method: "POST",
			contentType: "json",
			dataType: "json",
			data: {
				user: useridList,
			},
		});
		if (res.data.errcode === 0) {
			return true;
		}
		this.app.logger.error(
			"[企业微信 邀请成员] 错误 %s %j",
			res.data.errmsg,
			res.data.invaliduser
		);

		throw new CodoError(res.data.errmsg);
	}
}
